package com.ocm.commerceinteraction.ui;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.luckymoneysdk.bean.MoneyInfo;
import com.easemob.luckymoneysdk.constant.LMConstant;
import com.easemob.luckymoneyui.ui.activity.LMMoneyActivity;
import com.easemob.luckymoneyui.utils.LMMoneyManager;
import com.easemob.util.PathUtil;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.Constant;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.MainActivity;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.GroupDetailModel;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.MoneyUtils;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.player.Player;
import com.ocm.commerceinteraction.util.view.MyAlertVDialog;
import com.ocm.commerceinteraction.widget.ChatRowMoney;
import com.ocm.commerceinteraction.widget.ChatRowReceiveMoney;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import easeui.EaseConstant;
import easeui.domain.EaseUser;
import easeui.ui.EaseChatFragment;
import easeui.ui.EaseGroupRemoveListener;
import easeui.utils.EaseSmileUtils;
import easeui.utils.EaseUserUtils;
import easeui.widget.EaseChatInputMenu;
import easeui.widget.EaseChatMessageList;
import easeui.widget.EaseTitleBar;
import easeui.widget.chatrow.EaseChatRow;
import easeui.widget.chatrow.EaseCustomChatRowProvider;


@EFragment(R.layout.fragment_chat)
public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {
    //避免和基类定义的常量可能发生的冲突，常量从11开始定义
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;
    private static final int REQUEST_CODE_CONTEXT_MENU = 15;


    private static final int ITEM_SEND_MONEY = 16;
    private static final int REQUEST_CODE_SEND_MONEY = 17;
    private static final int MESSAGE_TYPE_RECV_MONEY = 18;
    private static final int MESSAGE_TYPE_SEND_MONEY = 19;
    private static final int MESSAGE_TYPE_SEND_LUCKY = 20;
    private static final int MESSAGE_TYPE_RECV_LUCKY = 21;
    @ViewById(R.id.title_bar)
    EaseTitleBar easeTitleBar;
//    @ViewById(R.id.message_list)
//    EaseChatMessageList messageList;


    @ViewById(R.id.input_menu)
    EaseChatInputMenu easeChatInputMenu;

    @ViewById(R.id.open_img)
    ImageView openImg;

    @ViewById(R.id.close_img)
    ImageView closeImg;

    ChatFragment homeFragment;
//    private String group_uniq_id;

    private Player player;
    SeekBar music_progress;
    private int fromChat;
    private static int maxVolume = 50; // 最大音量值
    private static int curVolume = 20; // 当前音量值
    private static int stepVolume = 0; // 每次调整的音量幅度
    private static AudioManager audioMgr = null; // Audio管理器，用了控制音量
    private static final String TAG = "ChatFragment";

    @AfterViews
    void initViewData() {
        setChatFragmentHelper(this);
        homeFragment = this;
        easeTitleBar.setTitle("聊天标题");
        easeTitleBar.setBackgroundColor(GlobalApplication.getContext().getResources().getColor(R.color.themeColor));
        easeTitleBar.setRightImageResource(R.drawable.ic_qun_info);
        fragmentArgs = getArguments();
        fromChat = fragmentArgs.getInt("from");
        if (fromChat == 2)
            initPlay();
        else{
            closeImg.setVisibility(View.GONE);
            openImg.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        //异步获取群人数方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMGroup returnGroup = EMGroupManager.getInstance().getGroupFromServer(toChatUsername);
                    EMGroupManager.getInstance().createOrUpdateLocalGroup(returnGroup);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    void initPlay(){

        music_progress = (SeekBar) getActivity().findViewById(R.id.music_progress);
        player = new Player(music_progress);
        // 获取最大音乐音量
        audioMgr = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 初始化音量大概为最大音量的1/2
        curVolume = maxVolume / 2;
        // 每次调整的音量大概为最大音量的1/6
        stepVolume = maxVolume / 6;

        new Thread(new Runnable() {
                @Override
                public void run() {
//                player.playUrl("http://abv.cn/music/光辉岁月.mp3");
                  player.playUrl("http://bchat.ocmcom.com/data/upload/vidio/djhot.mp3?time="+new Date());
                }
            }).start();
    }
    void toPlay(){
        if (player!=null)
         player.play();
    }
    void toPause(){
        if (player!=null)
         player.pause();
    }
    /**
     * 调整音量
     */
    private static void adjustVolume() {
        audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume,
                AudioManager.FLAG_PLAY_SOUND);
    }

    @Click({R.id.left_layout, R.id.right_layout,R.id.open_img,R.id.close_img})
    void Click(View view) {
        switch (view.getId()) {
            case R.id.open_img:
                if (fromChat == 2){
                    closeImg.setVisibility(View.VISIBLE);
                    openImg.setVisibility(View.GONE);
                    toPause();
                }

                break;
            case R.id.close_img:
                if (fromChat == 2){
                    closeImg.setVisibility(View.GONE);
                    openImg.setVisibility(View.VISIBLE);
                    toPlay();
                }

                break;
            case R.id.left_layout:
//                ChatActivity.getInstance().finish();
                if (player!=null)
                    player.stop();
                MainActivity.getFragmentMangerinstance().popBackStack();
                break;
            case R.id.right_layout:
                if (chatType == EaseConstant.CHATTYPE_GROUP) {
                    ChatActivity.switchFragment(this, new GroupInfoFragment_().builder().
                            groupDetailModel(groupDetailModel)
//                            .groupDetailModel(groupDetailModel)
                            .build());
                } else {
                    //清空和某个user的聊天记录(包括本地)，不删除conversation这个会话对象
                    final MyAlertVDialog ad = new MyAlertVDialog(getActivity());
                    ad.setTitle("");
                    ad.setMessage("确定要删除聊天记录吗");
                    ad.setNegativeButton("  确定     ", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            EMChatManager.getInstance().clearConversation(toChatUsername);
                            messageList.refresh();
                            ad.dismiss();
                        }
                    });
                    ad.setPositiveButton("  取消    ", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            ad.dismiss();
                        }
                    });

                }

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("zetan", "ChatFragment - onActivityResult - "+requestCode);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
                case ContextMenuActivity.RESULT_CODE_COPY: // 复制消息
                    clipboard.setText(((TextMessageBody) contextMenuMessage.getBody()).getMessage());
                    break;
                case ContextMenuActivity.RESULT_CODE_DELETE: // 删除消息
                    conversation.removeMessage(contextMenuMessage.getMsgId());
                    refreshUI();
                    break;
                default:
                    break;
            }
        }
        if(resultCode == Activity.RESULT_OK){
            switch (requestCode) {
                case REQUEST_CODE_SEND_MONEY://发送红包消息
                    if (data != null) {
                        String greetings = data.getStringExtra(LMConstant.EXTRA_MONEY_GREETING);
                        String moneyID = data.getStringExtra(LMConstant.EXTRA_CHECK_MONEY_ID);
                        EMMessage message = EMMessage.createTxtSendMessage("["+getResources().getString(R.string.hunxin_luckymoney)+"]"+greetings, toChatUsername);
                        message.setAttribute(LMConstant.MESSAGE_ATTR_IS_MONEY_MESSAGE, true);
                        message.setAttribute(LMConstant.EXTRA_SPONSOR_NAME, getResources().getString(R.string.hunxin_luckymoney));
                        message.setAttribute(LMConstant.EXTRA_MONEY_GREETING, greetings);
                        message.setAttribute(LMConstant.EXTRA_CHECK_MONEY_ID, moneyID);
                        sendMessage(message);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void registerExtendMenuItem() {
        super.registerExtendMenuItem();
        //红包
        if (chatType != Constant.CHATTYPE_CHATROOM){
            inputMenu.registerExtendMenuItem(R.string.attach_red_packet, R.drawable.em_chat_money_selector, ITEM_SEND_MONEY, extendMenuItemClickListener);
        }
    }
    /**
     * 刷新UI界面
     */
    public void refreshUI(){
        messageList.refresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        messageList.refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (player!=null)
           player.stop();
    }
    public static boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {

            case KeyEvent.KEYCODE_VOLUME_DOWN:

                curVolume -= stepVolume;
                if (curVolume <= 0) {
                    curVolume = 0;
                }
               break;
            case KeyEvent.KEYCODE_VOLUME_UP:

                curVolume += stepVolume;
                if (curVolume >= maxVolume) {
                    curVolume = maxVolume;
                }
                break;
        }
        // 调整音量
        adjustVolume();
        return true;
    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {

    }

    @Override
    public void onEnterToChatDetails() {

    }

    @Override
    public void onAvatarClick(String username) {

    }

    @Override
    public boolean onMessageBubbleClick(final EMMessage message){
        TextMessageBody txtBody = (TextMessageBody) message.getBody();
        if (message.getBooleanAttribute(LMConstant.MESSAGE_ATTR_IS_MONEY_MESSAGE, false)) {
            final ProgressDialog progressDialog = new ProgressDialog(getActivity());
            progressDialog.setCanceledOnTouchOutside(false);
            String moneyId = null;
            String messageDirect;
            String toAvatarUrl = "none";//测试用图片url:http://i.imgur.com/DvpvklR.png
            //接收者昵称 默认值为当前用户ID
            String toNickname = EMChatManager.getInstance().getCurrentUser();
            int cType;
            try {
                moneyId = message.getStringAttribute(LMConstant.EXTRA_CHECK_MONEY_ID);
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
            if (message.direct == EMMessage.Direct.SEND) {
                messageDirect = LMConstant.MESSAGE_DIRECT_SEND;
            } else {
                messageDirect = LMConstant.MESSAGE_DIRECT_RECEIVE;
            }
            if (chatType == Constant.CHATTYPE_SINGLE) {
                cType = LMConstant.CHATTYPE_SINGLE;
            } else {
                cType = LMConstant.CHATTYPE_GROUP;
            }
            EaseUser easeUser = EaseUserUtils.getUserInfo(EMChatManager.getInstance().getCurrentUser());
            if (easeUser != null) {
                toAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
                toNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
            }
            MoneyInfo moneyInfo = new MoneyInfo();
            moneyInfo.moneyID = moneyId;
            moneyInfo.toAvatarUrl = toAvatarUrl;
            moneyInfo.toNickName = toNickname;
            moneyInfo.moneyMsgDirect = messageDirect;
            moneyInfo.chatType = cType;
            Log.e(TAG, "openMoney之前" );
            LMMoneyManager.getInstance().openMoney(moneyInfo, getActivity(), new LMMoneyManager.LMReceiveMoneyCallBack() {
                @Override
                public void onSuccess(String senderId, String senderNickname) {
                    //领取红包成功 发送消息到聊天窗口
                    String receiverId = EMChatManager.getInstance().getCurrentUser();
                    //设置默认值为id
                    String receiverNickname = receiverId;
                    EaseUser receiverUser = EaseUserUtils.getUserInfo(receiverId);
                    if (receiverUser != null) {
                        receiverNickname = TextUtils.isEmpty(receiverUser.getNick()) ? receiverUser.getUsername() : receiverUser.getNick();
                    }
                    if (chatType == Constant.CHATTYPE_SINGLE) {
                        EMMessage msg = EMMessage.createTxtSendMessage(String.format(getResources().getString(R.string.money_msg_someone_take_money),receiverNickname), toChatUsername);
                        msg.setAttribute(LMConstant.MESSAGE_ATTR_IS_OPEN_MONEY_MESSAGE, true);
                        msg.setAttribute(LMConstant.EXTRA_LUCKY_MONEY_RECEIVER, receiverNickname);
                        msg.setAttribute(LMConstant.EXTRA_LUCKY_MONEY_SENDER, senderNickname);
                        sendMessage(msg);
                    } else {
                        Log.e(TAG, "群红包" );
                        //群红包的红包回执消息使用了透传消息，注册透传及收取透传可参考2.x最新demo
                        MoneyUtils.sendMoneyAckMessage(message, senderId, senderNickname, receiverId, receiverNickname, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                messageList.refresh();
                            }

                            @Override
                            public void onError(int i, String s) {

                            }

                            @Override
                            public void onProgress(int i, String s) {

                            }
                        });
                    }
                }

                @Override
                public void showLoading() {
                    progressDialog.show();
                }

                @Override
                public void hideLoading() {
                    progressDialog.dismiss();
                }

                @Override
                public void onError(String code, String message) {
                    Log.e(TAG, "onError: "+message );
                    //错误处理
                }
            });
            return true;
        }
        String span = txtBody.getMessage();
        String regex = "(?i)((https|http|ftp|rtsp|mms)?://)"
                + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
                + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
                + "|" // 允许IP和DOMAIN（域名）
                + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
                + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
                + "[a-z]{2,6})" // first level domain- .com or .museum
                + "(:[0-9]{1,4})?" // 端口- :80
                + "((/?)|" // a slash isn't required if there is no file name
                + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        String _regex = "(?i)http://[^\\u4e00-\\u9fa5]+";
        SpannableString result = null;
        String urlStr="";
        Matcher m = Pattern.compile(regex).matcher(span);
        while (m.find()){
            urlStr=m.group();
            Intent intent = new Intent();
            intent.putExtra("url", urlStr);
            intent.setClass(this.getActivity(),ChatWebActivity.class);
            startActivity(intent);
        }
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        Log.e(TAG, " 长按事件" );
        //消息框长按
        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message", message),
                REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        Log.e(TAG, "onExtendMenuItemClick");
        switch (itemId) {
            case ITEM_SEND_MONEY://发送红包
                sendMoney();
                break;
            default:
                break;
        }
        //不覆盖已有的点击事件
        return false;
    }

    protected void sendMoney() {
        Intent intent = new Intent(getActivity(), LMMoneyActivity.class);
        //发送者头像url
        String fromAvatarUrl = "";
        //发送者昵称 设置了昵称就传昵称 否则传id
        String fromNickname = "";
        EaseUser easeUser = EaseUserUtils.getUserInfo(EMChatManager.getInstance().getCurrentUser());
        if (easeUser != null) {
            fromAvatarUrl = TextUtils.isEmpty(easeUser.getAvatar()) ? "none" : easeUser.getAvatar();
            fromNickname = TextUtils.isEmpty(easeUser.getNick()) ? easeUser.getUsername() : easeUser.getNick();
        }
        MoneyInfo moneyInfo = new MoneyInfo();
        moneyInfo.fromAvatarUrl = fromAvatarUrl;
        moneyInfo.fromNickName = fromNickname;
        //接收者Id或者接收的群Id
        if (chatType == Constant.CHATTYPE_SINGLE) {
            moneyInfo.toUserId = toChatUsername;
            moneyInfo.chatType = LMConstant.CHATTYPE_SINGLE;
        } else if (chatType == Constant.CHATTYPE_GROUP) {
            EMGroup group = EMGroupManager.getInstance().getGroup(toChatUsername);
            moneyInfo.toGroupId = group.getGroupId();
            moneyInfo.groupMemberCount = group.getAffiliationsCount();
            moneyInfo.chatType = LMConstant.CHATTYPE_GROUP;
        }
        intent.putExtra(LMConstant.EXTRA_MONEY_INFO, moneyInfo);
        startActivityForResult(intent, REQUEST_CODE_SEND_MONEY);
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider()
    {
//        return null;
          return new CustomChatRowProvider();
    }


    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //红包、音、视频通话发送、接收共8种
            return 29;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if(message.getType() == EMMessage.Type.TXT){
                if (message.getBooleanAttribute(LMConstant.MESSAGE_ATTR_IS_MONEY_MESSAGE, false)) {
                    //发送红包消息
                    return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_MONEY : MESSAGE_TYPE_SEND_MONEY;
                } else if (message.getBooleanAttribute(LMConstant.MESSAGE_ATTR_IS_OPEN_MONEY_MESSAGE, false)) {
                    //领取红包消息
                    return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LUCKY : MESSAGE_TYPE_SEND_LUCKY;
                }
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if(message.getType() == EMMessage.Type.TXT){
                // 语音通话,  视频通话
                if (message.getBooleanAttribute(LMConstant.MESSAGE_ATTR_IS_MONEY_MESSAGE, false)) {//发送红包消息
                    return new ChatRowMoney(getActivity(), message, position, adapter);
                } else if (message.getBooleanAttribute(LMConstant.MESSAGE_ATTR_IS_OPEN_MONEY_MESSAGE, false)) {//领取红包消息
                    return new ChatRowReceiveMoney(getActivity(), message, position, adapter);
                }
            }
            return null;
        }
    }
}
